package com.destin.basic.security;

import com.destin.basic.config.RedisUtils;
import com.destin.basic.constans.RedisKey;
import com.destin.basic.exception.BusinessException;
import com.destin.basic.exception.TokenIsExpiredException;
import com.destin.basic.util.JwtTokenUtils;
import com.destin.basic.util.UserUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description: Jwt权限控制
 * @author: Destin
 * @date: 2021-06-30
 */
@Slf4j
public class JWTAuthorizationFilter extends BasicAuthenticationFilter {

    RedisUtils redisUtil;

    public JWTAuthorizationFilter(AuthenticationManager authenticationManager, RedisUtils redisUtil) {
        super(authenticationManager);
        this.redisUtil = redisUtil;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws IOException, ServletException {

        String tokenHeader = request.getHeader(SecurityProperties.header);
        // 如果请求头中没有Authorization信息则直接放行了
        if (tokenHeader == null || !tokenHeader.startsWith(SecurityProperties.tokenStartWith)) {
            chain.doFilter(request, response);
            return;
        }
        // 如果请求头中有token，则进行解析，并且设置认证信息
        try {
            SecurityContextHolder.getContext().setAuthentication(getAuthentication(tokenHeader));
        } catch (TokenIsExpiredException e) {
            //返回json形式的错误信息
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            log.error("token解析异常，原因：token缺失或token有误！");
            String reason = "统一处理，原因：" + "token缺失或token有误！";
            response.getWriter().write(new ObjectMapper().writeValueAsString(reason));
            response.getWriter().flush();
            return;
        }
        super.doFilterInternal(request, response, chain);
    }

    // 这里从token中获取用户信息并新建一个token
    private UsernamePasswordAuthenticationToken getAuthentication(String tokenHeader) throws TokenIsExpiredException {
        String token = tokenHeader.replace(SecurityProperties.tokenStartWith, "");
        boolean expiration = JwtTokenUtils.isExpiration(token);
        if (expiration)
        throw new TokenIsExpiredException("token超时了");
        String username = JwtTokenUtils.getUsername(token);
        LoginUserInfo loginUserInfo = (LoginUserInfo) redisUtil.get(RedisKey.getLoginUserKey(username));
        if (null == loginUserInfo)
            throw BusinessException.create("无法获取到用户信息");
        UserUtils.userId.set(loginUserInfo.getId());
        return new UsernamePasswordAuthenticationToken(loginUserInfo.getId(), token, null);
    }

}
